/**
 * Copyright (c) 2017, Alex. All rights reserved.
 */
package com.oschina.bottle.utils;

import static java.util.Objects.requireNonNull;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 涉及到金额相关运算的要使用BigDecimal类
 *
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2017/9/28
 * @since 1.0
 */
public class MoneyUtils {

    /**
     * 金额：求和运算
     */
    public static BigDecimal sum(Number... numbers) {
        requireNonNull(numbers,"the params must not be null");

        BigDecimal result = new BigDecimal("0");
        if (numbers.length > 0) {
            for (Number number : numbers) {
                result = result.add(new BigDecimal(String.valueOf(number)));
            }
        }

        return result;
    }

    /**
     * 金额：乘法运算
     */
    public static BigDecimal multiply(Number... numbers) {
        requireNonNull(numbers,"the params must not be null");
        if (numbers.length < 1) {
            throw new IllegalArgumentException("the params must not be null");
        }

        BigDecimal result = new BigDecimal("1");

        for (Number number : numbers) {
            result = result.multiply(new BigDecimal(String.valueOf(number)));
        }

        return result;
    }


    /**
     * 金额：除法运算
     */
    public static BigDecimal divide(Number numberA, Number numberB) {
        requireNonNull(numberA, "the numberB must not be null");
        requireNonNull(numberB, "the numberB must not be null");

        return new BigDecimal(String.valueOf(numberA)).divide(new BigDecimal(String.valueOf(numberB)));
    }

    /**
     * 元 to 分
     */
    public static Integer toFen(Double number) {
        requireNonNull(number,"the number must not be null");

        return new BigDecimal(number).setScale(2, RoundingMode.HALF_UP).movePointRight(2).intValue();
    }

    /**
     * 分 to 元
     */
    public static Double toYuan(Integer number) {
        requireNonNull(number,"the number must not be null");
        return new BigDecimal(number).movePointLeft(2).doubleValue();
    }
}
